﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;
using ParsePtb.attr;

namespace ParsePtb.util
{
    public static class DataTableUtils
    {
        /// <summary>
        /// DataTable转成List
        /// </summary>
        /// <typeparam name="T">泛型集合类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns>以实体类为元素的泛型集合</returns>
        public static List<T> ToDataList<T>(this DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                T s = Activator.CreateInstance<T>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => humpToUnderline(p.Name) == dt.Columns[i].ColumnName.ToUpper());
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                else
                                {
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                }
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                        }
                    }
                }
                list.Add(s);
            }
            return list;
        }

        /// <summary>
        /// DataTable转成Dto
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T ToDataDto<T>(this DataTable dt)
        {
            T s = Activator.CreateInstance<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return s;
            }
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                PropertyInfo info = plist.Find(p => humpToUnderline(p.Name) == dt.Columns[i].ColumnName.ToUpper());
                if (info != null)
                {
                    try
                    {
                        if (!Convert.IsDBNull(dt.Rows[0][i]))
                        {
                            object v = null;
                            if (info.PropertyType.ToString().Contains("System.Nullable"))
                            {
                                v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
                            }
                            else
                            {
                                v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
                            }
                            info.SetValue(s, v, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
                    }
                }
            }
            return s;
        }

        /// <summary>
        /// 将实体集合转换为DataTable
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">实体集合</param>
        public static DataTable ToDataTable<T>(List<T> entities)
        {
            var result = CreateTable<T>();
            FillData(result, entities);
            return result;
        }

        /// <summary>
        /// 创建表
        /// </summary>
        private static DataTable CreateTable<T>()
        {
            var result = new DataTable();
            var type = typeof(T);
            foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                var propertyType = property.PropertyType;
                if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    propertyType = propertyType.GetGenericArguments()[0];
                result.Columns.Add(property.Name, propertyType);
            }
            return result;
        }

        /// <summary>
        /// 填充数据
        /// </summary>
        private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
        {
            foreach (var entity in entities)
            {
                dt.Rows.Add(CreateRow(dt, entity));
            }
        }

        /// <summary>
        /// 创建行
        /// </summary>
        private static DataRow CreateRow<T>(DataTable dt, T entity)
        {
            DataRow row = dt.NewRow();
            var type = typeof(T);
            foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
                row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
            }
            return row;
        }


        /// <summary>
        /// 驼峰转下划线,首字母不转
        /// </summary>
        /// <param name="strItem">目标字符串</param>
        /// <returns></returns>
        public static string humpToUnderline(string strItem)
        {
            if (string.IsNullOrEmpty(strItem)) return "";
            string strItemTarget = "";  //目标字符串
            for (int j = 0; j < strItem.Length; j++)  //strItem是原始字符串
            {
                string temp = strItem[j].ToString();
                if (Regex.IsMatch(temp, "[A-Z]") && j != 0)
                {
                    temp = "_" + temp.ToLower();
                }
                strItemTarget += temp;
            }
            return strItemTarget.ToUpper();
        }

        /// <summary>
        /// DataTable转list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(DataTable dt)
        {
            List<T> list = new List<T>();
            if (dt == null)
            {
                return list;

            }
            BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

            Type type = typeof(T);
            /*            PropertyInfo[] propertyInfos = typeof(T).GetProperties(bindingFlags);
                        var plist = new List<PropertyInfo>(propertyInfos);*/

            TableFieldAttr tableFieldAttr = null;


            FieldInfo[] fieldInfos = type.GetFields(bindingFlags);

            Dictionary<string, PropertyInfo> dictionAry = new Dictionary<string, PropertyInfo>();

            for (int p = 0; p < fieldInfos.Length; p++)
            {
                tableFieldAttr = fieldInfos[p].GetCustomAttribute<TableFieldAttr>();
                if (tableFieldAttr != null && tableFieldAttr.ColumName != null)
                {
                    dictionAry.Add(tableFieldAttr.ColumName, type.GetProperty(SQLiteSqlUtils.UpperCaseFirst(fieldInfos[p].Name)));
                }

            }

            PropertyInfo currentProp = null;
            //实体
            T s;
            foreach (DataRow item in dt.Rows)
            {

                s = Activator.CreateInstance<T>();

                for (int i = 0; i < dt.Columns.Count; i++)
                {

                    if (dictionAry.ContainsKey(dt.Columns[i].ColumnName))
                    {

                        currentProp = dictionAry[dt.Columns[i].ColumnName];

                        object v = null;
                        if (currentProp.PropertyType.ToString().Contains("System.Nullable"))
                        {
                            v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(currentProp.PropertyType));
                        }
                        else
                        {
                            v = Convert.ChangeType(item[i], currentProp.PropertyType);
                        }
                        currentProp.SetValue(s, v, null);

                    }

                }
                list.Add(s);
            }
            return list;
        }




    }
}
